const fs = require('fs');
const path = require('path');
// const dayjs = require('dayjs');
const moment = require('moment');
module.exports = {
    // 上传 files请求文件,mkdir目录
    async _upload(files, mkdir) {
		const { config, app } = this;
		let mkdirPath = mkdir;
		if(mkdir) mkdirPath = mkdir + '/'
        // 上传基础目录
        const uplaodBasePath = 'app/public/upload/';
		let result = [];
		let target
		try {
        	for (const file of files) {
				// 生成文件名
				const filename = Date.now() + '' + Number.parseInt(Math.random() * 10000) + path.extname(file.filename);
				// 判断文件夹是否存在，不存在则直接创建文件夹
				if (!fs.existsSync(uplaodBasePath + mkdirPath)) fs.mkdirSync(path.join(config.baseDir, uplaodBasePath, mkdirPath));
				// 生成写入路径
				target = path.join(config.baseDir, uplaodBasePath, mkdirPath, filename);			
				// 写入流
				const writeStream = fs.createWriteStream(target);
				// 读取流
				const readStream = fs.createReadStream(file.filepath);// 创建可读流
				console.log(readStream)
				readStream.pipe(writeStream);
				// 保存图片路径
				const data = {
					path: ('public/upload/' + mkdirPath + filename),
					admin_id: 1,
					mkdir: mkdir? mkdir: 0, 
					filename,
					create_time: moment().format('YYYY-MM-DD HH:mm:ss') 
				}
				let res = await app.model.Imgs.create(data);
				result.push(res);
			}
			return{
				code: 200,
				data: result,
				msg: '上传成功',
			};
        }catch (err) {
			result = null;
			// 需要删除文件
			if (fs.existsSync(target)){
				fs.unlinkSync(target);
			}
			return {
				code: 500,
				data: err,
				msg: '上传失败',
			};
		}
      },
}